package com.atguigu.gmall.realtime.util;

import com.atguigu.gmall.realtime.common.Constant;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Archie
 * @date 2021-10-18 18:36
 * @description
 */
public class JDBCUtil {

	public static Connection getPhoenixConnection(String url) {
		String driver = Constant.PHOENIX_DRIVER;
		return getJdbcConnection(driver, url);
	}

	public static Connection getMysqlConnection(String url) {
		// FIXME
		return null;
	}

	public static Connection getJdbcConnection(String driver, String url) {
		try {
			Class.forName(driver);
			return DriverManager.getConnection(url);
		} catch (SQLException | ClassNotFoundException throwables) {
			throwables.printStackTrace();
		}
		return null;
	}

	public static <T> List<T> queryList(Connection conn,
										String sql,
										Object[] args,
										Class<T> tClass) {
		// User(id, name)

		List<T> result = new ArrayList<>();
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			// 给sql的占位符进行赋值
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i + 1, args[i]);
			}

			ResultSet resultSet = ps.executeQuery();

			// 获取元数据信息: 列名, 列的类型, 列的个数, ...
			ResultSetMetaData metaData = resultSet.getMetaData();

			while (resultSet.next()) { // 遍历行
				T t = tClass.newInstance();
				// 遍历列
				for (int i = 1; i <= metaData.getColumnCount(); i++) {
					// 取出列名:   对应着 T类型的属性名  (T 是Map , 对应着key)
					String columnName = metaData.getColumnLabel(i);
					// 取出列值: 给 T 中的属性赋值
					Object value = resultSet.getObject(columnName);
					BeanUtils.setProperty(t, columnName, value);
				}
				result.add(t);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}

		return result;
	}

}
